local user = require 'library.user'
local helper = require 'library.helpers'
local cache = require ('library.cache'):new()

local cacheplUgin = require('vanilla.v.plugin'):new()

function cacheplUgin:routerStartup(request, response)
    if request.method == 'GET' then
        --print_r('-----------' .. sprint_r(request.headers) .. '----------')
    else
        --print_r(request.headers)
    end
end

function cacheplUgin:routerShutdown(request, response)
end

function cacheplUgin:dispatchLoopStartup(request, response)
end

function cacheplUgin:preDispatch(request, response)


end

function cacheplUgin:afterControllerInit(request, response,controller)
	--response.is_cached=false
	controller:_init_cache(request.action_name,request.controller_name)
	if response.cache_name~='' and response.cache_life >0 then
		local ret=cache:get(response.cache_name);
		if ret and  type(ret) =="string" and ret~='' then
			response.body=ret
			response.is_cached=true
		end
	end	
end

function cacheplUgin:postDispatch(request, response,controller)
	if not response.is_cached then
		if response.cache_name~='' and response.cache_life>0 then
			cache:set(response.cache_name,response.body.."<!--cached at "..ngx.localtime().." -->",response.cache_life)
		end
	end
	response.body=helper:no_cache_replace(response.body)
end

function cacheplUgin:dispatchLoopShutdown(request, response)
	--session:save()
end

return cacheplUgin
